package com.syx.order.Service;

import com.syx.order.Dao.OrderMapper;
import com.syx.order.Model.OrderInfo;
import com.syx.order.Model.ProductInfo;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    RestTemplate restTemplate;

    @Resource
    DiscoveryClient discoveryClient;

    private AtomicInteger atomicInteger=new AtomicInteger(2);

    private List<ServiceInstance> instances ;

    //第一次请求进行初始化。
    @PostConstruct
    private void init(){
        instances=discoveryClient.getInstances("product-server");

    }




    /*public OrderInfo selectOrderById(Integer orderId){
        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
        List<ServiceInstance> instances = discoveryClient.getInstances("product-server");
        String uri = instances.get(0).getUri().toString();

        *//*String url="http://127.0.0.1:9090/product/"+orderInfo.getProductId();*//*
        String url=uri+"/product/"+orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);

        return orderInfo;



    }*/
    /*public OrderInfo selectOrderById(Integer orderId){
        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);

        int index=atomicInteger.getAndIncrement() % instances.size();
        String uri = instances.get(index).getUri().toString();

        *//*String url="http://127.0.0.1:9090/product/"+orderInfo.getProductId();*//*
        String url=uri+"/product/"+orderInfo.getProductId();
        log.info(url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);

        return orderInfo;



    }*/
    public OrderInfo selectOrderById(Integer orderId){
        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);


        String url="http://product-server/product/"+orderInfo.getProductId();
        log.info("远程调用"+url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);

        return orderInfo;



    }
}
